import json

import requests

url = "https://gpt-api.serendipitous-clue.com/event-stream"
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
    'uuid': 'hjj'
}
data = {
    'model': 'gpt-4',
    'temperature': 0.6,
    'presence_penalty': 0,
    'messages': [
        {'role': 'user', 'content': '你好'}
    ],
}


def doChatRequestHandle():
    # SSE数据请求
    chat_response = requests.post(url, json=data, headers=headers, stream=True)
    if chat_response.status_code != 200:
        raise Exception(f"Failed to connect to {url}, status code: {chat_response.status_code}")
    for line in chat_response.iter_lines():
        if line:
            yield line.decode('utf-8')[6:]


def getBalance():
    # 不带请求内容只有请求头的请求，是查询余额
    balance_response = requests.post(url, headers=headers, stream=True)
    if balance_response.status_code != 200:
        raise Exception(f"Failed to connect to {url}, status code: {balance_response.status_code}")
    for line in balance_response.iter_lines():
        if line:
            yield line.decode('utf-8')

def result():
    for chunk in doChatRequestHandle():
        if chunk == '[DONE]':
            break
        data = json.loads(chunk)
        print(data['choices'][0]['delta'].get('content', ''),end='')

if __name__ == "__main__":
    result()
